//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Utilities;
using DotNetNuke.UI.WebControls;
namespace DotNetNuke.Common.Lists
{
	public partial class ListEntries : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		public event EventHandler ListCreated;
		public event EventHandler ListEntryCreated;
		protected int DefinitionID
		{
			get
			{
				if (ViewState["DefinitionID"] == null)
				{
					ViewState["DefinitionID"] = Null.NullInteger;
				}
				return Convert.ToInt32(ViewState["DefinitionID"]);
			}
			set { ViewState["DefinitionID"] = value; }
		}
		protected bool EnableSortOrder
		{
			get
			{
				if (ViewState["EnableSortOrder"] == null)
				{
					ViewState["EnableSortOrder"] = false;
				}
				return Convert.ToBoolean(ViewState["EnableSortOrder"]);
			}
			set { ViewState["EnableSortOrder"] = value; }
		}
		protected ListInfo SelectedList
		{
			get { return GetList(SelectedKey, true); }
		}
		protected ListEntryInfoCollection SelectedListItems
		{
			get
			{
				ListEntryInfoCollection list = null;
				if (SelectedList != null)
				{
					ListController ctlLists = new ListController();
					list = ctlLists.GetListEntryInfoCollection(SelectedList.Name, SelectedList.ParentKey, SelectedList.PortalID);
				}
				return list;
			}
		}
		protected bool SystemList
		{
			get
			{
				if (ViewState["SystemList"] == null)
				{
					ViewState["SystemList"] = false;
				}
				return Convert.ToBoolean(ViewState["SystemList"]);
			}
			set { ViewState["SystemList"] = value; }
		}
		public string ListName
		{
			get
			{
				if (ViewState["ListName"] != null)
				{
					return ViewState["ListName"].ToString();
				}
				else
				{
					return "";
				}
			}
			set { ViewState["ListName"] = value; }
		}
		public int ListPortalID
		{
			get
			{
				if (ViewState["ListPortalID"] == null)
				{
					ViewState["ListPortalID"] = Null.NullInteger;
				}
				return Convert.ToInt32(ViewState["ListPortalID"]);
			}
			set { ViewState["ListPortalID"] = value; }
		}
		public string Mode
		{
			get
			{
				if (ViewState["Mode"] != null)
				{
					return ViewState["Mode"].ToString();
				}
				else
				{
					return "";
				}
			}
			set { ViewState["Mode"] = value; }
		}
		public string ParentKey
		{
			get
			{
				if (ViewState["ParentKey"] != null)
				{
					return ViewState["ParentKey"].ToString();
				}
				else
				{
					return "";
				}
			}
			set { ViewState["ParentKey"] = value; }
		}
		public string SelectedKey
		{
			get
			{
				if (ViewState["SelectedKey"] != null)
				{
					return ViewState["SelectedKey"].ToString();
				}
				else
				{
					return "";
				}
			}
			set { ViewState["SelectedKey"] = value; }
		}
		public bool ShowDelete
		{
			get
			{
				if (ViewState["ShowDelete"] != null)
				{
					return Convert.ToBoolean(ViewState["ShowDelete"]);
				}
				else
				{
					return false;
				}
			}
			set { ViewState["ShowDelete"] = value; }
		}
		private void BindGrid()
		{
			foreach (DataGridColumn column in grdEntries.Columns)
			{
				if (object.ReferenceEquals(column.GetType(), typeof(ImageCommandColumn)))
				{
					ImageCommandColumn imageColumn = (ImageCommandColumn)column;
					if (imageColumn.CommandName == "Delete")
					{
						imageColumn.OnClickJS = Localization.GetString("DeleteItem");
						if (SystemList)
						{
							column.Visible = false;
						}
						else
						{
							column.Visible = true;
						}
					}
					if (!String.IsNullOrEmpty(imageColumn.CommandName))
					{
						imageColumn.Text = Localization.GetString(imageColumn.CommandName, this.LocalResourceFile);
					}
				}
			}
			grdEntries.DataSource = SelectedListItems;
			grdEntries.DataBind();
			if (SelectedListItems == null)
			{
				this.lblEntryCount.Text = "0 " + Localization.GetString("Entries", this.LocalResourceFile);
			}
			else
			{
				this.lblEntryCount.Text = SelectedListItems.Count.ToString() + " " + Localization.GetString("Entries", this.LocalResourceFile);
			}
		}
		private void BindListInfo()
		{
			lblListName.Text = ListName;
			lblListParent.Text = ParentKey;
			rowListParent.Visible = (!String.IsNullOrEmpty(ParentKey));
			chkEnableSortOrder.Checked = EnableSortOrder;
			if (!SystemList && ShowDelete)
			{
				this.cmdDeleteList.Visible = true;
				ClientAPI.AddButtonConfirm(cmdDeleteList, Localization.GetString("DeleteItem"));
			}
			else
			{
				this.cmdDeleteList.Visible = false;
			}
			switch (Mode)
			{
				case "ListEntries":
					EnableView(true);
					break;
				case "EditEntry":
					EnableView(false);
					EnableEdit(false);
					break;
				case "AddEntry":
					EnableView(false);
					EnableEdit(false);
					if (SelectedList != null)
					{
						txtParentKey.Text = SelectedList.ParentKey;
					}
					else
					{
						rowEnableSortOrder.Visible = true;
					}
					txtEntryName.Text = ListName;
					rowListName.Visible = false;
					txtEntryValue.Text = "";
					txtEntryText.Text = "";
					cmdSaveEntry.CommandName = "SaveEntry";
					break;
				case "AddList":
					EnableView(false);
					EnableEdit(true);
					rowListName.Visible = true;
					txtParentKey.Text = "";
					txtEntryName.Text = "";
					txtEntryValue.Text = "";
					txtEntryText.Text = "";
					txtEntryName.ReadOnly = false;
					cmdSaveEntry.CommandName = "SaveList";
					ListController ctlLists = new ListController();
					{
						ddlSelectList.Enabled = true;
						ddlSelectList.DataSource = ctlLists.GetListInfoCollection();
						ddlSelectList.DataTextField = "DisplayName";
						ddlSelectList.DataValueField = "Key";
						ddlSelectList.DataBind();
						ddlSelectList.Items.Insert(0, new ListItem(Localization.GetString("None_Specified"), ""));
					}
					{
						ddlSelectParent.ClearSelection();
						ddlSelectParent.Enabled = false;
					}

					break;
			}
		}
		private void DeleteItem(int entryId)
		{
			if (SelectedListItems.Count > 1)
			{
				try
				{
					ListController ctlLists = new ListController();
					ctlLists.DeleteListEntryByID(entryId, true);
					DataBind();
				}
				catch (Exception exc)
				{
					Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
				}
			}
			else
			{
				DeleteList();
			}
		}
		private void DeleteList()
		{
			ListController ctlLists = new ListController();
			ctlLists.DeleteList(SelectedList, true);
			Response.Redirect(Common.Globals.NavigateURL(TabId));
		}
		private void EnableEdit(bool AddList)
		{
			this.rowListdetails.Visible = (!AddList);
			this.rowSelectList.Visible = AddList;
			this.rowSelectParent.Visible = AddList;
			this.rowEnableSortOrder.Visible = AddList;
			this.rowParentKey.Visible = false;
			this.cmdDelete.Visible = false;
		}
		private void EnableView(bool ViewMode)
		{
			this.rowListdetails.Visible = true;
			this.rowEntryGrid.Visible = ViewMode;
			this.rowEntryEdit.Visible = (!ViewMode);
		}
		private ListInfo GetList(string key, bool update)
		{
			ListController ctlLists = new ListController();
			int index = key.IndexOf(":");
			string _ListName = key.Substring(index + 1);
			string _ParentKey = Null.NullString;
			if (index > 0)
			{
				_ParentKey = key.Substring(0, index);
			}
			if (update)
			{
				ListName = _ListName;
				ParentKey = _ParentKey;
			}
			return ctlLists.GetListInfo(_ListName, _ParentKey, ListPortalID);
		}
		private void InitList()
		{
			if (SelectedList != null)
			{
				DefinitionID = SelectedList.DefinitionID;
				EnableSortOrder = SelectedList.EnableSortOrder;
				SystemList = SelectedList.SystemList;
			}
		}
		public override void DataBind()
		{
			InitList();
			BindListInfo();
			BindGrid();
		}
		protected void OnListCreated(EventArgs e)
		{
			if (ListCreated != null)
			{
				ListCreated(this, e);
			}
		}
		protected void OnListEntryCreated(EventArgs e)
		{
			if (ListEntryCreated != null)
			{
				ListEntryCreated(this, e);
			}
		}
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			try
			{
				if (!Page.IsPostBack)
				{
					Mode = "ListEntries";
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			grdEntries.ItemCommand += new DataGridCommandEventHandler(grdEntries_ItemCommand);
			ddlSelectList.SelectedIndexChanged += new EventHandler(ddlSelectList_SelectedIndexChanged);
			cmdAddEntry.Click += new EventHandler(cmdAddEntry_Click);
			cmdCancel.Click +=new EventHandler(cmdCancel_Click);
			cmdDelete.Click += new EventHandler(cmdDelete_Click);
			cmdDeleteList.Click += new EventHandler(cmdDeleteList_Click);
			cmdSaveEntry.Click += new EventHandler(cmdSaveEntry_Click);
		}
		private void grdEntries_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			try
			{
				ListController ctlLists = new ListController();
				int entryID = Convert.ToInt32(((DataGrid)source).DataKeys[e.Item.ItemIndex]);
				switch (e.CommandName.ToLower())
				{
					case "delete":
						Mode = "ListEntries";
						DeleteItem(entryID);
						break;
					case "edit":
						Mode = "EditEntry";
						ListEntryInfo entry = ctlLists.GetListEntryInfo(entryID);
						this.txtEntryID.Text = entryID.ToString();
						this.txtParentKey.Text = entry.ParentKey;
						this.txtEntryValue.Text = entry.Value;
						this.txtEntryText.Text = entry.Text;
						rowListName.Visible = false;
						this.cmdSaveEntry.CommandName = "Update";
						if (!SystemList)
						{
							this.cmdDelete.Visible = true;
							ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("DeleteItem"));
						}
						else
						{
							this.cmdDelete.Visible = false;
						}
						DataBind();
						break;
					case "up":
						ctlLists.UpdateListSortOrder(entryID, true);
						DataBind();
						break;
					case "down":
						ctlLists.UpdateListSortOrder(entryID, false);
						DataBind();
						break;
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void ddlSelectList_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			ListController ctlLists = new ListController();
			ListInfo selList = GetList(ddlSelectList.SelectedItem.Value, false);
			{
				ddlSelectParent.Enabled = true;
				ddlSelectParent.DataSource = ctlLists.GetListEntryInfoCollection(selList.Name, selList.ParentKey);
				ddlSelectParent.DataTextField = "DisplayName";
				ddlSelectParent.DataValueField = "EntryID";
				ddlSelectParent.DataBind();
			}
		}
		private void cmdAddEntry_Click(object sender, System.EventArgs e)
		{
			Mode = "AddEntry";
			DataBind();
		}
		private void cmdSaveEntry_Click(object sender, System.EventArgs e)
		{
			ListController ctlLists = new ListController();
			ListEntryInfo entry = new ListEntryInfo();
			{
				entry.DefinitionID = Null.NullInteger;
				entry.PortalID = ListPortalID;
				entry.ListName = txtEntryName.Text;
				entry.Value = txtEntryValue.Text;
				entry.Text = txtEntryText.Text;
			}
			if (Page.IsValid)
			{
				Mode = "ListEntries";
				switch (cmdSaveEntry.CommandName.ToLower())
				{
					case "update":
						entry.ParentKey = SelectedList.ParentKey;
						entry.EntryID = Int16.Parse(txtEntryID.Text);
						ctlLists.UpdateListEntry(entry);
						DataBind();
						break;
					case "saveentry":
						if (SelectedList != null)
						{
							entry.ParentKey = SelectedList.ParentKey;
							entry.ParentID = SelectedList.ParentID;
							entry.Level = SelectedList.Level;
						}
						if (chkEnableSortOrder.Checked)
						{
							entry.SortOrder = 1;
						}
						else
						{
							entry.SortOrder = 0;
						}
						ctlLists.AddListEntry(entry);
						DataBind();
						break;
					case "savelist":
						if (ddlSelectParent.SelectedIndex != -1)
						{
							int parentID = Int32.Parse(ddlSelectParent.SelectedItem.Value);
							ListEntryInfo parentEntry = ctlLists.GetListEntryInfo(parentID);
							entry.ParentID = parentID;
							entry.DefinitionID = parentEntry.DefinitionID;
							entry.Level = parentEntry.Level + 1;
							entry.ParentKey = parentEntry.Key;
						}
						if (chkEnableSortOrder.Checked)
						{
							entry.SortOrder = 1;
						}
						else
						{
							entry.SortOrder = 0;
						}
						ctlLists.AddListEntry(entry);
						SelectedKey = entry.ParentKey.Replace(":", ".") + ":" + entry.ListName;
						Response.Redirect(Common.Globals.NavigateURL(TabId, "", "Key=" + SelectedKey));
						break;
				}
			}
		}
		private void cmdDeleteList_Click(object sender, System.EventArgs e)
		{
			DeleteList();
		}
		private void cmdDelete_Click(object sender, System.EventArgs e)
		{
			DeleteItem(Convert.ToInt32(txtEntryID.Text));
		}
		private void cmdCancel_Click(object sender, System.EventArgs e)
		{
			try
			{
				Mode = "ListEntries";
				if (!String.IsNullOrEmpty(SelectedKey))
				{
					DataBind();
				}
				else
				{
					Response.Redirect(Common.Globals.NavigateURL(TabId));
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
	}
}
